import "taro-ui/dist/style/components/modal.scss";
import Taro from "@tarojs/taro";
import dayjs from "dayjs";
import {AtModal} from "taro-ui";
import {Button, Image, Text, View} from "@tarojs/components";
import {useCallback, useEffect, useMemo, useRef, useState} from "react";
import SeatBox from "@/components/seatBox";
import {getRealPx} from "@/utils/helper";
import './index.scss'

export default () => {
  const {router} = Taro.getCurrentInstance()
  const [seatData, setSeatData] = useState()
  const [planInfo, setPlanInfo] = useState({})
  const [seatBoxOptions, setSeatBoxOptions] = useState({})
  const [selectSeat, setSelectSeat] = useState([])
  const [planId, setPlanId] = useState()
  const [inited, setInited] = useState(true)
  const [catelist, setCatelist] = useState([])
  const [showReset, setShowReset] = useState(0)
  const [hallConfig, setHallConfig] = useState({})
  const [totalPrice, setTotalPrice] = useState(0)
  const [maxCanBuy, setMaxCanBuy] = useState(6)
  const [noPayOrderNo, setNoPayOrderNo] = useState()
  const selectSeatRef=useRef([])

  const seatResource = {
    selected: '',
    unselected: '',
    bought: '',
    error: ''
  }

  const onClickSeat = (evt, pos) => {
    if (evt.label.includes('unselected')) {
      let list=[...selectSeatRef.current]
      let arr = evt.areaId!==undefined?[...seatData[evt.areaId].sseat]:[...seatData];
      if (list.find(item => item.id == evt.id)) {
        list=list.filter(item => item.id != evt.id)
        if (evt.ext.flag == 1) {
          //情侣首座(左
          const lseat=arr[pos.row][pos.col + 1]
          if(lseat&&list.find(item => item.id == lseat.id)){
            list=list.filter(item => item.id != lseat.id)
          }
        } else if (evt.ext.flag == 2) {
          //情侣第二座(右
          const rseat=arr[pos.row][pos.col - 1]
          if(rseat&&list.find(item => item.id == rseat.id)){
            list=list.filter(item => item.id != rseat.id)
          }
        }
      } else {
        if (list.length >= maxCanBuy) {
          Taro.showToast({ title: `最多只能选择${maxCanBuy}个座位`, icon: 'none' });
          return;
        }
        list.push({...evt, label: 'selected','inr':pos.row,'inc':pos.col,pos})
        if (evt.ext.flag == 1) {
          //情侣首座(左
          const lseat=arr[pos.row][pos.col + 1]
          if(lseat){
            list.push({...lseat, label: 'selected','inr':pos.row,'inc':pos.col+1,pos:{row:pos.row,col:pos.col+1}})
          }
        } else if (evt.ext.flag == 2) {
          //情侣第二座(右
          const rseat=arr[pos.row][pos.col - 1]
          if(rseat){
            list.push({...rseat, label: 'selected','inr':pos.row,'inc':pos.col-1,pos:{row:pos.row,col:pos.col-1}})
          }
        }
      }
      list.sort((a, b) => a.inc - b.inc);
      list.sort((a, b) => a.inr - b.inr);
      selectSeatRef.current=list
      let price=0
      list.forEach(item=>{
        price+=item.ext.price
      })
      setTotalPrice(price.toFixed(2))
      setSelectSeat(selectSeatRef.current)
    }
  }

  const lockSeat = async () => {
    if (!selectSeat.length) {
      return Taro.$toast('请先选择座位')
    }
    Taro.showLoading({title:'加载中...'})
    Taro.$post('/act/orders', {
      "activityId": planId,
      "seatList": selectSeat.map(item=>item.ext)
    },'1').then(res => {
      Taro.hideLoading()
      if (res.code == '1') {
        Taro.redirectTo({
          url: `/orderSubPack/order-confirm/index?orderId=${res.content.orderId}`
        })
      } else {
        Taro.$toast(res.message)
      }
    })
  }

  useEffect(() => {
    setPlanId(router.params.id)
  }, [])

  const init = async () => {
    Taro.showLoading({title:'加载中...'})
    setInited(false)
    setSelectSeat([])
    const planInfoRes = await Taro.$get(`/act/activities/${planId}`,'','1')
    if (planInfoRes.code != '1') return
    setPlanInfo(planInfoRes.content)
  }
  useEffect(() => {
    if(planInfo.id){
      Taro.showLoading({title:'加载中...'})
      Taro.$get(`/act/orders/userUnPaidOrder`).then(async res=>{
        if(res.code == '1'){
          if(res.content.length){
            Taro.hideLoading()
            setNoPayOrderNo(res.content[0])
          }else{
            if(planInfo.hall.type==3){
              getType3Seats({id:planId})
            }else{
              getSeats({id:planId})
            }
          }
        }else{
          Taro.$toast(res.message)
        }
      })
    }
  }, [planInfo]);
  const handleCancel=()=>{
    const orderNo=noPayOrderNo
    setNoPayOrderNo()
    console.log('aaaa',orderNo)
    Taro.redirectTo({
      url: `/orderSubPack/order-confirm/index?orderId=${orderNo}`
    })
  }
  const handleConfirm=()=>{
    const orderNo=noPayOrderNo
    setNoPayOrderNo()
    Taro.$put(`/act/orders/cancel/${orderNo}`)
    if(planInfo.hall.type==3){
      getType3Seats({id:planId})
    }else{
      getSeats({id:planId})
    }
  }
  const getBeforeAndNextSeat = (seat)=> {
    let arr = [];
    let row = seat.inr;
    let col = seat.inc;
    let startCol = col - 2;
    let endCol = col + 2;
    for (; startCol <= endCol; startCol += 1) {
      const seats=seat.areaId!==undefined?this.areaSeats[seat.areaId].sseat:this.seats
      console.log(seats,row,startCol)
      let st = seats[row][startCol];
      if (st) {
        let code = null;
        let status = this.renderSeatStatus(st);
        if (this.selects.filter((item) => item.ext_id == st.ext_id).length != 0) {
          code = 's';
        } else if (status == 'selected' || status == 'unavailable' || status == 'unEnable') {
          code = '1';
        } else if (status == 'available') {
          code = '0';
        } else {
          code = '1';
        }
        arr.push({ ...st, code });
      }
    }
    return arr;
  }
  const checkCanSelect= (seats)=> {
    const willCheckArr = [];
    for (let i = 0; i < seats.length; i++) {
      let seatArr = getBeforeAndNextSeat(seats[i]);
      if (!seatArr || seatArr.length == 0) {
        continue;
      }
      let checkCode = '';
      for (let j = 0; j < seatArr.length; j++) {
        checkCode += seatArr[j].code;
      }
      willCheckArr.push(checkCode);
    }

    for (let i = 0; i < willCheckArr.length; i++) {
      let checkCode = willCheckArr[i];
      let errCode = [];
      let regex = new RegExp('s', 'g');
      let size = !checkCode.match(regex) ? 0 : checkCode.match(regex).length;
      console.log('checkCode:', checkCode, 'seat size:', size);
      if (size == 1) {
        errCode = ['10s00', '00s01', '10s01', '10s0', '0s01', '00s0', '0s00'];
        if (errCode.indexOf(checkCode) != -1) {
          Taro.showToast({ title: '座位旁边不要留空', icon: 'none' });
          return false;
        }
      } else if (size == 2) {
        if (
          checkCode.indexOf('10s1s') === -1 &&
          checkCode.indexOf('s1s01') === -1 &&
          checkCode !== '10ss' &&
          checkCode !== 'ss01' &&
          checkCode !== '01ss0' &&
          checkCode !== '0ss10' &&
          checkCode !== '11ss01' &&
          checkCode !== '10ss11'
        ) {
          if (
            checkCode.indexOf('10s') !== -1 ||
            checkCode.indexOf('s01') !== -1 ||
            checkCode.indexOf('s0s') !== -1
          ) {
            Taro.showToast({ title: '不要留下单个空位', icon: 'none' });
            return false;
          }
        }
      } else if (size === 3) {
        if (
          checkCode.indexOf('ss11s0') === -1 &&
          checkCode.indexOf('0s11ss') === -1 &&
          checkCode !== 's0010ss' &&
          checkCode !== 'ss0100s' &&
          checkCode !== '0s0010ss' &&
          checkCode !== 'ss0100s0' &&
          checkCode !== '10sss11' &&
          checkCode !== '11sss01'
        ) {
          //00ss11s0
          if (
            checkCode.indexOf('10s') !== -1 ||
            checkCode.indexOf('s01') !== -1 ||
            checkCode.indexOf('s0s') !== -1 ||
            checkCode === '00sss0' ||
            checkCode === '0sss00'
          ) {
            Taro.showToast({ title: '不要留下单个空位', icon: 'none' });
            return false;
          }
        }
      } else if (size === 4) {
        if (
          checkCode.indexOf('sss11s0') === -1 &&
          checkCode.indexOf('0s11sss') === -1 &&
          checkCode.indexOf('ss11ss0') === -1 &&
          checkCode.indexOf('0ss11ss') === -1 &&
          checkCode !== '10ssss' &&
          checkCode !== 'ssss01'
        ) {
          //00ss11s0
          if (
            checkCode.indexOf('10s') !== -1 ||
            checkCode.indexOf('s01') !== -1 ||
            checkCode.indexOf('s0s') !== -1 ||
            checkCode === '00ssss0' ||
            checkCode === '0ssss00'
          ) {
            Taro.showToast({ title: '不要留下单个空位', icon: 'none' });
            return false;
          }
        }
      } else if (size === 5) {
        if (
          checkCode !== '00sss1ss00' &&
          checkCode !== '00ss1sss00' &&
          checkCode !== '0sss1110ss' &&
          checkCode !== 'ss0111sss0'
        ) {
          //00ss11s0
          if (
            checkCode.indexOf('10s') !== -1 ||
            checkCode.indexOf('s01') !== -1 ||
            checkCode.indexOf('s0s') !== -1 ||
            checkCode === '00sssss0' ||
            checkCode === '0sssss00'
          ) {
            Taro.showToast({ title: '不要留下单个空位', icon: 'none' });
            return false;
          }
        }
      } else if (size === 6) {
        if (
          checkCode !== 'ssss1110ss' &&
          checkCode !== 'ss0111ssss' &&
          checkCode !== '00s001sssss' &&
          checkCode !== 'ssss100s00'
        ) {
          if (
            checkCode.indexOf('10s') !== -1 ||
            checkCode.indexOf('s01') !== -1 ||
            checkCode.indexOf('s0s') !== -1 ||
            checkCode === '00ssssss0' ||
            checkCode === '0ssssss00'
          ) {
            Taro.showToast({ title: '不要留下单个空位', icon: 'none' });
            return false;
          }
        }
      }
    }
    return true;
  }

  const getType3Seats =  async (options)=>{
    Taro.showLoading({title:'加载中...'})
    await Taro.$get(`/act/halls/detail?scheduleId=${options.id}`,'',1).then(res=>{
      if(res.code === '1'){
        const clList=(res.content.priceList || [])
        setCatelist(clList)
        setMaxCanBuy(res.content.max_can_buy||6)
        const clMap={}
        clList.forEach(item=>{
          clMap[item.area]=item.price*1
        })
        setSeatData(res.content.areaSeats.map((area,areaId)=>{
          const sseat=[]
          for(let j=1;j<=area.maxRow;j++){
            const row=[]
            for(let i=1;i<=area.maxColumn;i++){
              const seat=area.sseat.find(item=>item.r==j&&item.c==i)
              let price = planInfo.price*1
              if(res.content.priceList?.length){
                price = res.content.priceList.filter(result=>result?.priceId == area?.priceId)[0]?.salePrice || planInfo.price*1
              }
              row.push(seat?{
                id:seat.i,
                label: seat.s==1?'unselected':'bought',
                areaId,
                priceId:area.priceId,
                ext:{
                  area:seat.a,
                  ext_id:seat.i,
                  column:seat.c,
                  row:seat.r,
                  name:seat.n,
                  flag:seat.flag,
                  price
                }
              }:null)
            }
            sseat.push(row)
          }
          area.sseat=sseat
          Object.assign(area,{
            rows:sseat.length,
            cols:sseat[0].length
          })
          return area
        }))
        const query = Taro.createSelectorQuery();
        query.selectAll('.part-3').boundingClientRect((rectRes) => {
          setSeatBoxOptions({
            isArea:true,
            resource: seatResource,
            boxW: getRealPx(750),
            boxH: rectRes[0].height,
            boxT: rectRes[0].top,
            bg:res.content.backgroudUrl,
            bgWidth:parseFloat(res.content.width),
            bgHeight:parseFloat(res.content.height),
            minMapSize: {
              w: getRealPx(400),
              h: getRealPx(200),
            }
          })
          Taro.hideLoading()
          setInited(true)
        }).exec()
      }else{
        Taro.$toast(res.message)
        setTimeout(() => {
          Taro.navigateBack()
        }, 1000);
      }
    })
  }

  const getSeats = async (options)=>{
    Taro.showLoading({title:'加载中...'})
    await Taro.$get(`/act/activities/seat?id=${options.id}`,'','1').then(res => {
      if (res.code == '1') {
        const seatInfo = {
          maxCol: 0,
          maxRow: 0,
          minCol: 100,
          minRow: 100,
          seats: {}
        }
        const tmpSeatData = []
        setCatelist(res.content.areas || [])
        setHallConfig(res.content.hallConfig || {})
        res.content.seats.seat.forEach(item => {
          const row = parseInt(item.row)
          const col = parseInt(item.column)
          seatInfo.minRow = row > seatInfo.minRow ? seatInfo.minRow : row
          seatInfo.minCol = col > seatInfo.minCol ? seatInfo.minCol : col
          seatInfo.maxRow = row < seatInfo.maxRow ? seatInfo.maxRow : row
          seatInfo.maxCol = col < seatInfo.maxCol ? seatInfo.maxCol : col
          seatInfo.seats[`${row}_${col}`] = item
        })
        for (let row = seatInfo.minRow; row <= seatInfo.maxRow; row++) {
          let rowSeats = []
          for (let col = seatInfo.minCol; col <= seatInfo.maxCol; col++) {
            const seat = seatInfo.seats[`${row}_${col}`]
            let price = planInfo.price*1
            if(res.content.areas?.length){
              price = res.content.areas.filter(result=>result?.area == seat?.area)[0]?.price || planInfo.price*1
            }
            rowSeats.push(seat ? {
              // id:seat.i,
              // label: seat.status==1?'unselected':(seat.status==0?'bought':'error'),
              // ext:{
              //   ext_id:seat.i,
              //   column:seat.c,
              //   row:seat.r,
              //   name:seat.n,
              //   flag:seat.flag,
              //   price:planInfo.price*1
              // },
              id:seat.ext_id,
              label: seat.status==1?'unselected':'bought',
              ext:{
                area:seat.area,
                ext_id:seat.ext_id,
                column:seat.column,
                row:seat.row,
                name:seat.name,
                flag:seat.flag,
                price
              }
            } : null)
          }
          tmpSeatData.push(rowSeats)
        }
        setSeatData(tmpSeatData)
        const query = Taro.createSelectorQuery();
        query.selectAll('.part-3').boundingClientRect((rectRes) => {
          setSeatBoxOptions({
            isArea:false,
            resource: seatResource,
            boxW: getRealPx(750),
            boxH: rectRes[0].height,
            boxT: rectRes[0].top,
            minMapSize: {
              w: getRealPx(400),
              h: getRealPx(200),
            }
          })
          Taro.hideLoading()
          setInited(true)
        }).exec()
      }else{
        Taro.$toast(res.message)
        setTimeout(() => {
          Taro.navigateBack()
        }, 1000);
      }
    })
  }

  useEffect(() => {
    if (planId) {
      init()
    }
  }, [planId]);

  const handleReset=()=>{
    setShowReset(0)
  }

  return (
    <View className='page'>
      <View className='page-content'>
        <AtModal isOpened={!!noPayOrderNo}>
          <View className="popup-title">您还有一笔未完成的选座购票，是否继续该笔购买</View>
          <View className="popup-footer">
            <View className="button" onClick={handleCancel}>继续购买</View>
            <View className="button" onClick={handleConfirm}>重新选座</View>
          </View>
        </AtModal>
        <View className='part-1'>
          <View className='topView' id='topView'>
            <View className='xz-head'>
              <View className='legend not-bar' style={catelist.length>2?'justify-content:flex-start':'justify-content:center'}>
                <View className='item'>
                  <Image src={require("@/images/ticket/bought.png")} className='seatIcon' />
                  <Text>已售</Text>
                </View>
                {
                  catelist.map((item) => {
                    return (
                      <View className='item' key={item.url}>
                        <Image src={item.url} className='seatIcon' />
                        <Text>{item.name} {item.salePrice || item.price}元</Text>
                      </View>
                    )
                  })
                }
                {
                  !catelist.length && <>
                    <View className='item'>
                      <Image src={require("@/images/ticket/unselected.png")} className='seatIcon' />
                      <Text>可选</Text>
                    </View>
                    <View className='item'>
                      <Image src={require("@/images/ticket/bought.png")} className='seatIcon' />
                      <Text>不可选</Text>
                    </View>
                  </>
                }
              </View>
              {
                !!(!!showReset && planInfo.hall && planInfo.hall.type == 3) &&
                <View className='reset' onClick={handleReset}>
                  回到全局
                </View>
              }

              {
                !!hallConfig.topDirectionStatus &&
                <View className='head-screen'>
                  银幕方向
                  {
                    !!showReset &&
                    <View className='reset' onClick={handleReset}>回到全局</View>
                  }
                </View>
              }
            </View>
          </View>
        </View>
        <View className='part-3'>
          {
            !inited ? '' :
              <SeatBox seatData={seatData} catelist={catelist} options={seatBoxOptions} selectSeat={selectSeat}
                onClickSeat={onClickSeat} onHandleShowReset={setShowReset} showReset={showReset}
              ></SeatBox>
          }
        </View>
        <View className='part-4'>
          <View className='zw'>
            <View className='zw-header'>
              <View className='name'>{planInfo.title}</View>
              <View className='text'>
                {planInfo.dateStr}
              </View>
              {
                !!selectSeat.length&&
                <View className='planInfos'>
                  <View className='selected-seats not-bar'>
                    {
                      selectSeat.map((item,idx)=>{
                        return (
                          <View className='seletd' key={idx} onClick={()=>{
                            onClickSeat({...item,label:'unselected'},item.pos)
                          }}>
                            <View className='seletd-info'>{item.ext.name} <Text class='bol'>￥{item.ext.price}</Text></View>
                            <Image src={require("@/images/ticket/close.png")} className='se-seat-del' />
                          </View>
                        )
                      })
                    }
                  </View>
                </View>
              }
            </View>
            <View className='buyBtn' onClick={lockSeat}>
              {
                !!selectSeat.length&&
                <Text style='margin-right: 10rpx;'>￥{totalPrice}元</Text>
              }
              {selectSeat.length<1?"请先选座":"确认选座"}
            </View>
          </View>
        </View>
      </View>
    </View>
  )
}
